//
//  NetworkingTool.m
//  UI16_NetworkingTool
//
//  Created by dllo on 15/12/29.
//  Copyright © 2015年 yy. All rights reserved.
//

#import "NetworkingTool.h"

@implementation NetworkingTool

+ (void)networkingWithStrURL:(NSString *)strURL delegate:(id<NetworkingToolDelegate>)delegate{
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            // 代理人去执行协议方法
            [delegate bringResult:result];
        });
    }];
    // 任务的执行
    [task resume];
}

+ (void)networkingWithStrURL:(NSString *)strURL block:(Block)block{
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            // 通过"block"把值返回
            block(result);
        });
    }];
     // 任务的执行
    [task resume];
}

+ (void)networkingWithStrURL:(NSString *)strURL type:(MethodType)type bodyStr:(NSString *)bodyStr block:(Block)block{
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (type == POSTType) {
        [request setHTTPMethod:@"POST"];
        NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:bodyData];
    }
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            // 通过"block"把值返回
            block(result);
        });
    }];
    // 任务的执行
    [task resume];
}

@end
